package com.factory.test.activity;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.R;
import com.factory.test.base.BaseTestActivity;
import com.factory.test.databinding.ActivityCardBinding;
import com.yecontech.library_card.CardHandler;
import com.yecontech.library_card.IDCard;

/**
 * 刷卡测试
 */
public class CardActivity extends BaseTestActivity {

    private ActivityCardBinding binding;
    private CardHandler cardHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_card);



        Bundle bundle = new Bundle();
        bundle.putString(CardHandler.KEY_I2C_NODE, "/dev/i2c-1");
        cardHandler = new CardHandler(context, bundle, new CardHandler.OnReadCardListener() {
            @Override
            public void onType(int type) {
                showType(type);
            }

            @Override
            public void onRead(String readNo) {
                appendCard(readNo);
            }

            @Override
            public void onReadIdCard(IDCard idCard) {
                appendCard(idCard.toString());
            }
        });
    }

    private void showType(int type){
        handler.post(new Runnable() {
            @Override
            public void run() {
                switch (type){
                    case CardHandler.TYPE_I2C:{
                        binding.cardType.setText("I2C");
                        break;
                    }

                    case CardHandler.TYPE_SERIAL_PORT:{
                        binding.cardType.setText("SERIAL PORT (串口)");
                        break;
                    }

                    default:{
                        binding.cardType.setText("无刷卡设备");
                    }
                }
            }
        });
    }

    private void appendCard(final String cardNo){
        handler.post(new Runnable() {
            @Override
            public void run() {
                binding.textView.append(cardNo);
                binding.textView.append("\r\n");
                binding.scrollView.fullScroll(View.FOCUS_DOWN);
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        cardHandler.stop(); //todo 关闭界面需要释放，防止内存泄漏
    }
}
